<template>
  <el-card v-if="props.accountType == 'edit'" v-loading="configLoading" element-loading-background="rgba(255,255,255,1)">
    <template #header>
      <div class="max-w-[100%] truncate flex justify-between pr-1">
        <span>账号配置 - {{ props.accountInfo.accountName }}</span>
        <el-icon class="hover:text-[var(--el-color-primary)] cursor-pointer text-[20px]" @click="setSecend"><CloseBold /></el-icon>
      </div>
    </template>
    <el-form ref="PayAppAccountFormRef" :model="form" :rules="rules">
      <div class="grid grid-cols-5 gap-x-[20px]">
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option v-for="item in app_account_status" :label="item.label" :value="parseInt(item.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="限制额度" prop="status">
          <el-switch v-model="form.showTotal"></el-switch>
        </el-form-item>
        <el-form-item label="总额度" prop="totalLimit" v-if="form.showTotal">
          <el-input-number v-model="form.totalLimit" placeholder="总额度" />
        </el-form-item>
        <el-form-item label="额度增长率" prop="increaseRate" v-if="form.showTotal">
          <el-input-number v-model="form.increaseRate" placeholder="额度增长率" />
        </el-form-item>
        <el-form-item label="额度刷新时间" prop="refreshTime" v-if="form.showTotal">
          <el-time-select v-model="form.refreshTime" style="width: 100%" start="00:00" step="00:30" end="23:59" placeholder="请选择额度刷新时间" />
        </el-form-item>
        <el-form-item label="请求失败下线" prop="failLimit">
          <el-input-number v-model="form.failLimit" placeholder="失败次数限制" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" placeholder="排序" />
        </el-form-item>

        <el-form-item label="自动上线" v-if="form.showTotal">
          <el-radio-group v-model="form.autoUp">
            <el-switch v-model="form.autoUp" :active-value="1" :inactive-value="0"></el-switch>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="跳转方式" :prop="payMethods?.length ? 'payMethod' : ''">
          <el-select v-model="form.payMethod" @change="changePayMethod" clearable placeholder="请选择跳转方式">
            <el-option v-for="item in payMethods" :value="item.value" :label="item.label"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="强制货币" prop="isForce">
          <el-switch v-model="form.isForce" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>

        <el-form-item v-if="form.isForce == 1" filterable label="货币类型" prop="forceCurrency">
          <el-select v-model="form.forceCurrency" placeholder="请选择货币类型" filterable>
            <el-option v-for="item in currencyList" :label="item.code" :value="item.code"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开启订单金额限制" prop="minMoney">
          <el-switch v-model="moneyConstraint"></el-switch>
        </el-form-item>
        <el-form-item v-if="moneyConstraint" label="订单金额限制" prop="minMoney">
          <div class="flex gap-[20px]">
            <el-input v-model="form.minMoney" type="number" placeholder="最小订单金额" />
            <span class="">至</span>
            <el-input v-model="form.maxMoney" type="number" placeholder="最小订单金额" />
          </div>
        </el-form-item>
      </div>
      <!-- <div v-if="!moneyConstraint" class="grid grid-cols-3 gap-6 items-start">
        <el-form-item label="价格插件">
          <div class="flex items-start gap-5">
            <el-input v-model="form.pricePlugin" type="textarea" />
            <span class="leading-[18px]"
              >自动修改订单价格(单位美元);格式0-15:9.99表示价格在0到15美元间自动修改为9.99美元，多个价格规则可换行添加。</span
            >
          </div>
        </el-form-item>
        <el-form-item label="强制修改价格">
          <el-switch v-model="form.priceForce" :active-value="1" :inactive-value="0"></el-switch>
        </el-form-item>
      </div> -->
      <!--自定义-->
      <div class="grid grid-cols-5 gap-x-[20px]">
        <el-form-item
          v-for="item in accountConfig.customFields"
          :label="item.label"
          :prop="'customFieldsFront[' + item.value + ']'"
          clearable
          :rules="[
            {
              required: item.require,
              message: '请填写' + item.label,
              trigger: 'blur'
            }
          ]"
        >
          <el-input v-model="form.customFieldsFront[item.value]" :placeholder="item.label" />
        </el-form-item>
      </div>

      <div v-if="showReceiveType">
        <div class="flex justify-between">
          <span>收款方式</span>
          <el-button size="small" icon="Plus" type="primary" @click="addPayReceive">添加</el-button>
        </div>
        <el-table v-loading="loading" :data="form.receiveListFront" style="margin-top: 10px">
          <el-table-column label="支付名称" align="center" show-overflow-tooltip prop="name" />
          <el-table-column label="币种" align="center" prop="currencies" show-overflow-tooltip />
          <el-table-column label="商户国家" align="center" prop="country" show-overflow-tooltip />
          <el-table-column label="支付代码" align="center" prop="code" show-overflow-tooltip />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="mt-2 flex justify-end">
        <el-button type="primary" @click="saveAccountConfig">保存</el-button>
      </div>
    </el-form>
  </el-card>

  <el-card v-if="props.accountType == 'add'" v-loading="configLoading" element-loading-background="rgba(255,255,255,1)">
    <template #header>
      <div class="max-w-[100%] truncate flex justify-between pr-1">
        <span>新增账号</span>
        <el-icon class="hover:text-[var(--el-color-primary)] cursor-pointer text-[20px]" @click="setSecend"><CloseBold /></el-icon>
      </div>
    </template>
    <el-button type="primary" plain @click="addAccountNumber">添加账号</el-button>
    <el-table
      v-loading="accountLoading"
      :data="PayAccountList"
      ref="accountTable"
      class="mt-[10px]"
      @selection-change="handleSelectionChange"
      @cell-click="selectAccountRow"
    >
      <el-table-column type="selection" />
      <el-table-column label="备注" align="center" prop="remark" />
      <!-- <el-table-column label="代理名称" align="center" prop="agentName" /> -->
      <el-table-column v-if="false" label="账号ID" align="center" prop="accountId" />
      <el-table-column label="账号名称" align="center" show-overflow-tooltip prop="accountName" />
      <el-table-column label="支付平台" align="center" prop="payTypeId">
        <template #default="{ row }">
          <div>{{ payList.filter((item) => item.typeId == row.payTypeId)[0]?.name || row.payTypeId }}</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="{ row }">
          <el-tag v-if="row.status" type="success">活跃</el-tag>
          <el-tag v-else type="danger">已封禁</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="API类型" align="center" prop="apiType" min-width="130">
        <template #default="{ row }">
          <el-tag v-if="row.apiType" type="primary">{{ row.payConfig.apiConfig.find((item) => item.value == row.apiType).label }}</el-tag>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getAccountList" />
  </el-card>

  <!-- 收款方式弹窗 -->
  <el-dialog v-model="showPayReceive" append-to-body title="选择收款方式">
    <el-table
      v-loading="loading"
      :data="PayReceiveList"
      :stripe="true"
      style="margin-top: 10px"
      height="70vh"
      @selection-change="handleSelectionReceiveChange"
      @cell-click="selectRow"
      ref="receiveTable"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="支付名称" align="center" show-overflow-tooltip prop="name" />
      <el-table-column label="币种" align="center" prop="currencies" show-overflow-tooltip />
      <el-table-column label="商户国家" align="center" prop="country" show-overflow-tooltip />
      <el-table-column label="支付代码" align="center" prop="code" show-overflow-tooltip />
    </el-table>
    <template #footer>
      <el-button type="primary" @click="submitReceive">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { getCurrency } from '@/api/pay/PayApp';
import { listPayAccount } from '@/api/pay/PayAccount';
import { getPayAccount } from '@/api/pay/PayAccount';
import { addPayAppAccount, getPayAppAccountNoBinds, updatePayAppAccount, addBatchAccount } from '@/api/pay/PayAppAccount/index';
import { listPayReceive } from '@/api/pay/PayReceive';
const { proxy } = getCurrentInstance();
const { app_account_status, sys_country } = toRefs(proxy?.useDict('app_account_status', 'sys_country'));
const props = defineProps({
  payList: {
    type: Array,
    default: () => []
  },
  accountInfo: {
    type: Object,
    default: () => {}
  },
  accountType: {
    type: String,
    default: ''
  },
  plateInfo: {
    type: Object,
    default: () => {}
  }
});
const emits = defineEmits(['success', 'loadingSuccess', 'setSecend']);

watch(
  () => props.accountType,
  (val) => {
    if (val) {
      init();
    }
  }
);
watch(
  () => props.accountInfo.accountId,
  (val) => {
    if (val) {
      init();
    }
  }
);
const moneyConstraint = ref(false);
const showReceiveType = computed(() => {
  return (
    form.value.payMethod &&
    !configLoading.value &&
    payMethods.value &&
    !payMethods.value.find((item) => item.value == form.value.payMethod)?.notShowReceive
  );
});
const form = ref({
  status: undefined,
  totalLimit: undefined,
  increaseRate: undefined,
  refreshTime: '00:00',
  minMoney: undefined,
  maxMoney: undefined,
  totalMoney: undefined,
  payMethod: undefined,
  receiveList: undefined,
  failLimit: undefined,
  sort: undefined,
  customFieldsFront: {},
  receiveListFront: []
});
const rules = ref({
  status: [{ required: true, message: '状态不能为空', trigger: 'change' }],
  totalLimit: [{ required: true, message: '总额度不能为空', trigger: 'blur' }],
  increaseRate: [{ required: true, message: '额度增长率不能为空', trigger: 'blur' }],
  refreshTime: [{ required: true, message: '额度刷新时间不能为空', trigger: 'blur' }],
  minMoney: [{ required: true, message: '最小订单金额不能为空', trigger: 'blur' }],
  maxMoney: [{ required: true, message: '最大订单金额不能为空', trigger: 'blur' }],
  totalMoney: [{ required: true, message: '收款总金额不能为空', trigger: 'blur' }],
  payMethod: [{ required: true, message: '支付方式不能为空', trigger: 'blur' }],
  failLimit: [{ required: true, message: '失败次数限制不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
  forceCurrency: [{ required: true, message: '请选择货币类型', trigger: 'blur' }]
});

const queryParams = reactive({
  pageSize: 10,
  pageNum: 1,
  groupTypeId: '',
  appId: ''
});
const PayAccountList = ref([]);
const accountLoading = ref(false);
const total = ref(0);
const getAccountList = async () => {
  accountLoading.value = true;
  queryParams.groupTypeId = props.plateInfo.id;
  queryParams.groupId = props.plateInfo.groupId;
  let res = await getPayAppAccountNoBinds(queryParams);
  PayAccountList.value = res.rows.map((item) => {
    item.payConfig = props.payList.find((payType) => payType.typeId == item.payTypeId).config
      ? JSON.parse(props.payList.find((payType) => payType.typeId == item.payTypeId)?.config.replace(/\/\/\*\*\*.*\*\*\*.*\n/g, ''))
      : '';
    return item;
  });
  total.value = res.total;
  accountLoading.value = false;
};

const accountNumberList = ref([]);
const handleSelectionChange = (val) => {
  accountNumberList.value = val;
};
const addAccountNumber = async () => {
  configLoading.value = true;
  await addBatchAccount({
    accountIds: accountNumberList.value.map((item) => item.accountId),
    groupId: props.plateInfo.groupId,
    groupTypeId: props.plateInfo.id
  })
    .then(() => {
      ElMessage.success('添加成功');
      emits('success');
      getAccountList();
    })
    .finally(() => {
      configLoading.value = false;
    });
};

// 收款方式
const loading = ref(false);
const PayReceiveList = ref([]);
const getPayReceiveList = async () => {
  loading.value = true;
  const res = await listPayReceive(queryParams.value);
  if (form.value.receiveListFront.length) {
    let ids = form.value.receiveListFront.map((item) => item.id);
    PayReceiveList.value = res.rows.filter((item) => {
      return !ids.includes(item.id);
    });
  } else {
    PayReceiveList.value = res.rows;
  }
  if (props.plateInfo.code == 'square') {
    PayReceiveList.value = PayReceiveList.value.filter((item) => {
      return item.code == 'cashapp' || item.code == 'card' || item.code == 'apple_pay' || item.code == 'google_pay';
    });
  }
  if (props.plateInfo.code == 'stripe' && form.value.payMethod == 2) {
    PayReceiveList.value = PayReceiveList.value.filter((item) => {
      return item.code == 'cashapp';
    });
  }
  loading.value = false;
};
const showPayReceive = ref(false);
const selectReceiveList = ref([]);
const handleSelectionReceiveChange = (val) => {
  selectReceiveList.value = val;
};
const submitReceive = () => {
  if (form.value.receiveListFront) {
    form.value.receiveListFront = form.value.receiveListFront.concat(...selectReceiveList.value);
  } else {
    form.value.receiveListFront = selectReceiveList.value;
  }
  showPayReceive.value = false;
};
const handleDelete = (index) => {
  form.value.receiveListFront.splice(index, 1);
};
const addPayReceive = () => {
  getPayReceiveList();
  showPayReceive.value = true;
};

// 支付方式
const payMethods = ref([]);

// 查询账号详情
const accountData = ref({});
const accountConfig = ref({});
const getAccountInfo = async (aipConfig) => {
  let res = await getPayAccount(props.accountInfo.accountId);
  accountData.value = res.data;
  if (aipConfig) {
    if (aipConfig.find((item) => item.value == res.data.apiType)) {
      payMethods.value = aipConfig
        .find((item) => item.value == res.data.apiType)
        ?.payMethod.map((item) => {
          item.value = parseInt(item.value);
          return item;
        });
      accountConfig.value = res.data.config ? JSON.parse(res.data?.config.replace(/\/\/\*\*\*.*\*\*\*.*\n/g, '')) : {};
      form.value.payMethod ? form.value.payMethod : (form.value.payMethod = payMethods.value[0].value);
    }
    if (form.value.totalLimit > 0) {
      form.value.showTotal = true;
    } else {
      form.value.showTotal = false;
    }
  }
};

// 保存账号配置
const blackCountry = ref([]);
const buttonLoading = ref(false);
const PayAppAccountFormRef = ref(null);
const saveAccountConfig = () => {
  PayAppAccountFormRef.value?.validate(async (valid) => {
    if (valid) {
      if (moneyConstraint.value && form.value.minMoney == '0.00' && form.value.maxMoney == '0.00') {
        ElMessage.error('额度最小值和最大值不能同时为0');
        return;
      }
      if (!moneyConstraint.value) {
        form.value.minMoney = '0.00';
        form.value.maxMoney = '0.00';
      }
      form.value.blackCountry = blackCountry.value.join(',');
      form.value.groupId = props.plateInfo.groupId;
      form.value.accountId = props.accountInfo.accountId;
      form.value.customFields = JSON.stringify(form.value.customFieldsFront);
      form.value.receiveList = JSON.stringify(form.value.receiveListFront);
      if (!form.value.showTotal) {
        form.value.totalLimit = 0;
        form.value.increaseRate = 0;
        form.value.autoUp = 0;
        form.value.refreshTime = '';
      } else if (form.value.showTotal && form.value.totalLimit == 0) {
        ElMessage.error('请设置总额度!,总额度必须大于0');
        return;
      }

      configLoading.value = true;
      buttonLoading.value = true;
      await updatePayAppAccount(form.value).finally(() => (configLoading.value = false));
      ElMessage.success('保存配置成功');
      emits('success');
      configLoading.value = false;
    }
  });
};
let configLoading = ref(true);
const init = async () => {
  configLoading.value = true;
  setTimeout(async () => {
    if (props.accountType == 'edit') {
      form.value.receiveListFront = [];
      Object.assign(form.value, props.accountInfo);
      form.value.customFieldsFront = form.value.customFields ? JSON.parse(form.value.customFields) : {};
      blackCountry.value = form.value?.blackCountry ? form.value?.blackCountry.split(',') : [];
      props.accountInfo.receiveList && typeof props.accountInfo.receiveList == 'string'
        ? (form.value.receiveListFront = JSON.parse(props.accountInfo.receiveList))
        : '';
      let config = JSON.parse(props.payList.find((item) => item.typeId == props.plateInfo.typeId)?.config.replace(/\/\/\*\*\*.*\*\*\*.*\n/g, ''));
      payMethods.value = config?.apiConfig;
      moneyConstraint.value = !(form.value.minMoney == '0.00' && form.value.maxMoney == '0.00');
      await getAccountInfo(config?.apiConfig);
      configLoading.value = false;
    } else {
      await getAccountList();
      configLoading.value = false;
    }
    emits('loadingSuccess');
  }, 100);
};

/**货币类型 */
const currencyList = ref([]);
const getCurrencyList = async () => {
  let res = await getCurrency();
  currencyList.value = res.data;
};

/**选中收款方式 */
const receiveTable = ref(null);
const selectRow = (row) => {
  receiveTable.value.toggleRowSelection(row);
};

/**
 * 更改跳转方式
 */
const changePayMethod = () => {
  form.value.receiveListFront = [];
};

const accountTable = ref();
const selectAccountRow = (row) => {
  accountTable.value.toggleRowSelection(row);
};

const setSecend = () => {
  emits('setSecend');
};

onMounted(() => {
  init();
  getCurrencyList();
});
</script>

<style lang="scss" scoped>
.el-card {
  min-height: 100%;
  position: relative;
  padding-bottom: 40px;
}
.pagination-container {
  position: absolute;
  left: 50%;
  bottom: 10px;
  transform: translateX(-50%);
}
</style>
